//
//  EcgMeasureVc.m
//  CareRingApp
//
//  Created by Linktop on 2024/3/6.
//

#import "CAEcgMeasureVc.h"
#import "Colors.h"
#import <QMUIKit/QMUIKit.h>
#import <Masonry/Masonry.h>
#import "CARingSDK.h"
#import "CAEcgRecord.h"
#import "CAEcgParamObj.h"
#import "UIViewController+Custom.h"
#import "ConfigModel.h"
#import "LTRingEcgDrawLineView.h"
#import "LTHmEcgGridView.h"
#import "CABLeService.h"
#import "CADeviceInfo+description.h"
//#import "DeviceCenter.h"
//#import "AccountCenter.h"

#import "EcgNoTouchTipView.h"

#import "AppDelegate.h"
//#import "SymptomsBtnView.h"
//#import "EcgSymptomChooseView.h"
#import "ImgTitleItem.h"
#import "CARingEcgDrawHistoryView.h"
#import "SepLineView.h"
//#import "EcgParamObj+Transform.h"
//#import "EcgMedicObj.h"
//#import "ECGMedicVc.h"
#import "CADeviceInfo+description.h"
#import "UIView+LayoutDirection.h"
#import "EcgNetReq.h"
#import "NSKAlgoSDKECG.h"

NSString * const NSKAlgolicenseKey = @"4DYD5nkbZHYoJBqIxT3nc/QIB58doR7BiRxuH62Ayhs=";//神念key


@interface CAEcgMeasureVc ()<CABleScanProtocal, CABleDataProtocal, NSKAlgoSDKECGDelegate>
@property(strong, nonatomic)QMUIButton *startBtn, *doneBtn, *xSpeedBtn, *yGainBtn;

@property(strong, nonatomic)UILabel *topLabel, *hrDescLbl, *resTipLbl, *chargeTipLbl;

@property(strong, nonatomic)UIImageView *hrImageView;
@property(strong, nonatomic) ImgTitleItem *hrItem;

@property(strong, nonatomic)LTRingEcgDrawLineView *realMeaDrawLineView;
@property(strong, nonatomic) LTHmEcgGridView *realGridView;

@property(strong, nonatomic) CARingEcgDrawHistoryView *hisDrawLineView; // 测量结束全览图

@property(strong, nonatomic)NSArray <NSDictionary *>* xspeedArray, *yGainArray;
@property(assign, nonatomic) HORIZONTAL_SPEED xSpeed;
@property(assign, nonatomic) VERTIAL_GAIN yGain;

@property(weak, nonatomic)EcgNoTouchTipView *noTouchTipView;
@property(strong, nonatomic)NSNumber *wearHand;  // -1 = left hand,  1 = right hand.

@property(strong, nonatomic)UISegmentedControl *wearHandSeg;

@property(strong, nonatomic)NSMutableArray<CAEcgAlgorithmResults *> *ecgResultArray;
@property(strong, nonatomic)NSMutableArray<NSNumber *> *netFiltWaveArray; // 网络请求滤波用

@property(assign, nonatomic)BOOL measuring;

@property(strong, nonatomic) CAEcgRecord *ecgRecord;


@property(assign, nonatomic) CA_ECG_MEA_STA state;  // 界面显示状态机

@property(strong, nonatomic)UIScrollView *scrollView;
@property(strong, nonatomic) UIView *mainContent;

@property(strong, nonatomic)NSKAlgoSDKECG *algoEcgSdkObj; // 滤波使用


// 云端/本地 区分
@property(assign, nonatomic) BOOL useLocalAlgothem;// yes = 使用戒指算法
@property(assign, nonatomic) int sampleRate; // 采样率
@property(assign, nonatomic) int measuSecondsLimit;  // 测量时长 秒
@property(assign, nonatomic) BOOL isRequestingNet;
@property(assign, nonatomic) NSInteger ignoreCount;

@end

@implementation CAEcgMeasureVc

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.blackColor;
//    DebugNSLog(@"sn: %@ , mac = %@", CARingSDK.instance.currentDevice.snString, CARingSDK.instance.currentDevice.macAddress);
    [self initConstData];
    [self initUI];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
    CARingSDK.instance.bleDataDelegate = self;
    CARingSDK.instance.blescanDelegate = self;
    
    BOOL isconnected = CARingSDK.instance.currentDevice.isConnected;
    self.startBtn.enabled = isconnected;
    
    if (self.state == CA_ECG_MEA_STA_INIT) {
        self.state = CA_ECG_MEA_STA_INIT;
    }
    [UIApplication sharedApplication].idleTimerDisabled = YES; // 常亮

    if (self.state == CA_ECG_MEA_STA_INIT && CARingSDK.instance.currentDevice.isCharging) {
        self.chargeTipLbl.hidden = NO;
    } else {
        self.chargeTipLbl.hidden = YES;
    }

    // check ecg key secret
    if (![CARingSDK.instance hasECGKeyAndSecret]) {
        [self showAlertWarningWithTitle:@"Tips" Msg:@"You cannot perform measurement because the parameters KEY and SECRET required for requesting the server API cannot be read.\r\nYou need to fill in your own KEY and SECRET in the API call: registECGKey: Secret: and then recompile the project.\r\nFor the acquisition of these two parameters, please contact our technical support." btnCancel:@"Ok" Compelete:^{
            
        }];
        return;
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if(self.state != CA_ECG_MEA_STA_INIT) {
        [self stopEcgMeasure]; //离开关闭测量
        [self sumAndShowResult];

    }
    [UIApplication sharedApplication].idleTimerDisabled = NO; // 关闭常亮

}

-(void)segSelect:(UISegmentedControl *)seg
{
    NSInteger idx = seg.selectedSegmentIndex;
    if (idx == 0) {
        self.wearHand = @(-1);
    }
    if (idx == 1) {
        self.wearHand = @(1);
    }
        
    self.realMeaDrawLineView.direction = self.wearHand.intValue;
    self.hisDrawLineView.drawLineView.direction = self.wearHand.intValue;
}

- (void)initConstData {
    self.wearHand = @(-1); // left hand is default set
    _xspeedArray = @[@{@"title" : @"25mm/s", @"idx" : @(HORIZONTAL_SPEED_DEFAULT)},
                    @{@"title" : @"50mm/s", @"idx" : @(HORIZONTAL_SPEED_DOUBLE)},
    ];
    _yGainArray = @[@{@"title" : @"5 mm/mv", @"idx" : @(VERTIAL_GAIN_HALF)},
                    @{@"title" : @"10 mm/mv", @"idx" : @(VERTIAL_GAIN_DEFAULT)},
                    @{@"title" : @"20 mm/mv", @"idx" : @(VERTIAL_GAIN_DOUBLE)},
    ];
    
    self.xSpeed = HORIZONTAL_SPEED_DEFAULT;
    self.yGain = VERTIAL_GAIN_DEFAULT;
    
    if (self.deviceInfo.ecgCalcType == CA_ECG_CALC_ON_DEVICE) {
        // The ring comes with an ecg algorithm
        self.useLocalAlgothem = YES;
    }
    
    if (self.deviceInfo.ecgCalcType == CA_ECG_CALC_ON_NET) {
        // Filtering, the results are all used in the cloud
        self.useLocalAlgothem = NO;
    }
    
    if (self.useLocalAlgothem) {
        // (self.dataCountPerSecond * self.measuSecondsLimit) //ECG_MESURING_DURA_SECS_FOR_LOCAL
        self.sampleRate = 512; // 采样率
        self.measuSecondsLimit = ECG_MESURING_DURA_SECS_FOR_LOCAL;  // 测量时长 秒
    } else {
        self.sampleRate = 500; // 采样率
        self.measuSecondsLimit = 40; // 测量40秒
    }
    
}

-(void)initUI {
    WEAK_SELF
    [self customNavStyleNormal:@"ECG measurement" BackBlk:^{
        STRONG_SELF
        [strongSelf stopEcgMeasure];// 停止测量
        [strongSelf sumAndShowResult];

        
//        }
        [strongSelf.navigationController popViewControllerAnimated:YES];
    }];
    
//    [self arrowback:^{
//        STRONG_SELF
////        if(strongSelf.state != ECG_MEA_STA_INIT) {
////        if(self.state == ECG_MEA_STA_MEASURING || self.state ==  ECG_MEA_STA_WAIT_LEADON) {
//        
//        if ([DeviceCenter instance].appDataDelegate == strongSelf) {
//            [DeviceCenter instance].appDataDelegate = nil;
//        }
//        [strongSelf stopEcgMeasure];// 停止测量
//        [strongSelf sumAndShowResult];
//
//        
////        }
//        [strongSelf.navigationController popViewControllerAnimated:YES];
//    }];
    
    [self.view addSubview:self.scrollView];
    
    [self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
    }];
    
    self.mainContent = [UIView new];
    [self.scrollView addSubview:self.mainContent];
    [self.mainContent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainContent.superview);
        make.centerX.equalTo(self.mainContent.superview.mas_centerX);
        make.width.equalTo(self.mainContent.superview.mas_width);
    }];
    
    
//    [self.mainContent addSubview:self.measuProgressView];
//    [self.measuProgressView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.top.trailing.equalTo(self.measuProgressView.superview);
//        make.height.equalTo(@1);
//    }];
//    self.measuProgressView.transform = CGAffineTransformMakeScale(1.0, 0.8);

    
    
    self.topLabel = [UILabel new];
    self.topLabel.textAlignment =  NSTextAlignmentLeft;
    [self.mainContent addSubview:self.topLabel];
    
//    [self.mainContent addSubview:self.infoBtn];
   

    UIView *topCnt = [UIView new];
    [self.mainContent addSubview:topCnt];
    [self.mainContent addSubview:self.startBtn];
    [self.mainContent addSubview:self.wearHandSeg];
    
    [self.wearHandSeg mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.mainContent.mas_centerX);
        make.height.equalTo(@35);
        make.top.equalTo(self.wearHandSeg.superview.mas_safeAreaLayoutGuideTop).offset(20);
        make.width.equalTo(@180);
    }];
    
    [self.topLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading);
        make.height.equalTo(@44);
        make.top.equalTo(self.wearHandSeg.mas_bottom).offset(10);
    }];
    
//    [self.infoBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
//      
//        make.trailing.equalTo(topCnt.mas_trailing);
//        make.centerY.equalTo(self.topLabel.mas_centerY);
//        
//    }];

    CGFloat  cntHeight = [self.hisDrawLineView.gridView lengthBySquareCount:5* 6];
    
    [topCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.superview.mas_leading).offset(10);
        make.trailing.equalTo(topCnt.superview.mas_trailing).inset(10);
        make.top.equalTo(self.topLabel.mas_bottom).offset(0);
        make.height.equalTo( @(cntHeight) );// 30个小格
    }];
    
    [topCnt layoutIfNeeded];
   
    
    // 实时
    [topCnt addSubview:self.realMeaDrawLineView];
    
    //ecg grid
    LTHmEcgGridView *gridView = [[LTHmEcgGridView alloc] init];
    [topCnt addSubview:gridView];
    self.realGridView = gridView;
    
    // 历史
    [topCnt addSubview:self.hisDrawLineView];
    
    [self.hisDrawLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.hisDrawLineView.superview);
        
    }];
    
    CGFloat gridIntegetWidth =  [LTHmEcgGridView integetLengthFrom:topCnt.bounds.size.width];
    //layout
    [self.realMeaDrawLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.realMeaDrawLineView.superview.mas_centerX);
        
        make.width.equalTo(@(gridIntegetWidth));
//        make.bottom.equalTo(self.realMeaDrawLineView.superview.mas_bottom);
        make.height.equalTo(@(cntHeight));
        //        make.bottom.equalTo(startBtn.mas_top).offset(-3);
        make.top.equalTo(self.realMeaDrawLineView.superview.mas_top).offset(0);
    }];
    
   
    
    
    [self.realGridView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.realMeaDrawLineView.mas_centerX);
        make.centerY.equalTo(self.realMeaDrawLineView.mas_centerY);
        make.width.equalTo(self.realMeaDrawLineView.mas_width);
        make.height.equalTo(self.realMeaDrawLineView.mas_height);
    }];
    
    // 充电提示
    [self.mainContent addSubview:self.chargeTipLbl];
    [self.chargeTipLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading).offset(0);
        make.top.equalTo(topCnt.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(0);
    }];
//    UIImageView *hrView = [UIImageView new];
//    hrView.image = [UIImage imageNamed:@"ecg_hr"];
    [self.mainContent addSubview:self.hrItem];
//    self.hrImageView = hrView;
    [self.hrItem mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading).offset(5);
        make.top.equalTo(topCnt.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
    }];
//    [self.view addSubview:self.heartRateLbl];
    [self.mainContent addSubview:self.hrDescLbl];
    
//    [self.heartRateLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.equalTo(hrView.mas_trailing).offset(5);
//        make.centerY.equalTo(hrView.mas_centerY);
//    }];
    
    [self.hrDescLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.hrItem.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
    }];
    
    SepLineView *sephrDesc = [self creatSepLine];
    [self.hrDescLbl.superview addSubview:sephrDesc];
    [sephrDesc mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.hrDescLbl.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
   
    [self.mainContent addSubview:self.resTipLbl];
    [self.resTipLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.hrDescLbl.mas_bottom).offset(15);
        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
    }];
    
    SepLineView *sepRestip = [self creatSepLine];
    sepRestip.isDash = NO;
    [self.hrDescLbl.superview addSubview:sepRestip];
    [sepRestip mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem.mas_leading);
        make.top.equalTo(self.resTipLbl.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
    
   
//    [self.mainContent addSubview:self.symptomSelectView];
//    [self.symptomSelectView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.equalTo(self.hrItem.mas_leading);
//        make.trailing.equalTo(topCnt.mas_trailing).inset(5);
//        make.top.equalTo(sepRestip.mas_bottom).offset(5);
//    }];
   

    [self.startBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.equalTo(@44);
        make.width.equalTo(self.startBtn.superview.mas_width).multipliedBy(3.0/4);
//        make.bottom.equalTo(self.startBtn.superview.mas_bottom).inset(30);
        make.top.equalTo(topCnt.mas_bottom).offset(150);
        
    }];
        
    [self.mainContent addSubview:self.xSpeedBtn];
    [self.mainContent addSubview:self.yGainBtn];
    
    [self.xSpeedBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.startBtn);
        make.height.equalTo(self.startBtn);
        make.top.equalTo(self.startBtn.mas_bottom).offset(10);
        
        make.bottom.equalTo(self.startBtn.superview.mas_bottom).inset(30);

    }];
    
    [self.yGainBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.startBtn);
        make.height.equalTo(self.startBtn);
        make.top.equalTo(self.xSpeedBtn);
        make.leading.equalTo(self.xSpeedBtn.mas_trailing).offset(4);
        make.width.equalTo(self.xSpeedBtn);
    }];
    
    [self.mainContent addSubview:self.doneBtn];
    [self.doneBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.startBtn);
    }];
    
    [self.mainContent layoutIfNeeded];
    [self.view layoutIfNeeded];
    [self.scrollView layoutIfNeeded];

    
}

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return NO;
}

-(void)setAlgoObjSampleRate:(int)sampleRate Obj:(NSKAlgoSDKECG *)algoObj
{
    if (!algoObj) {
        return;
    }
    [algoObj setupSDKProperty:NSKAlgolicenseKey withSampleRate:sampleRate enableSmoothed:1];
}

-(void)chooseXspeed:(QMUIButton *)btn {
    
    WEAK_SELF
    UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (int  i = 0; i < _xspeedArray.count; i++) {
        NSDictionary *dict = _xspeedArray[i];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:dict[@"title"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            STRONG_SELF
            strongSelf.xSpeed = [dict[@"idx"] unsignedIntValue];
            [strongSelf.realMeaDrawLineView setHorizonalSpeed:strongSelf.xSpeed VertialGain:strongSelf.yGain];
            [strongSelf.hisDrawLineView setHorizonalSpeed:strongSelf.xSpeed VertialGain:strongSelf.yGain];
            [strongSelf.xSpeedBtn setTitle:dict[@"title"] forState:UIControlStateNormal];
        }];

        [alertVc addAction:action];
    }
    
 
    
   
    UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:actionCancel];

    [self presentViewController:alertVc animated:YES completion:nil];
    
}

-(void)chooseYgain:(QMUIButton *)btn {
    WEAK_SELF
    UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (int  i = 0; i < _yGainArray.count; i++) {
        NSDictionary *dict = _yGainArray[i];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:dict[@"title"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            STRONG_SELF
            strongSelf.yGain = [dict[@"idx"] unsignedIntValue];
            [strongSelf.realMeaDrawLineView setHorizonalSpeed:strongSelf.xSpeed VertialGain:strongSelf.yGain];
            [strongSelf.hisDrawLineView setHorizonalSpeed:strongSelf.xSpeed VertialGain:strongSelf.yGain];
            [strongSelf.yGainBtn setTitle:dict[@"title"] forState:UIControlStateNormal];
        }];

        [alertVc addAction:action];
    }
    
 
    
   
    UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:actionCancel];

    [self presentViewController:alertVc animated:YES completion:nil];
    
}


-(void)startEcg:(QMUIButton *)btn {
    
//    [self showEcgUseDescView];
//    
//    return;
    
    if (!btn.isSelected) {
        // 开始测量
        [self startEcgMeasure];
        return;
    }
    
    if (btn.isSelected) {
        // 停止测量
        [self stopEcgMeasure];
        [self sumAndShowResult];
        // 提前结束
        self.state = CA_ECG_MEA_STA_INIT;
        // 显示hud
        
        return;
    }
    
//    btn.selected = !btn.isSelected;
    
}

-(void)startEcgMeasure {
    
    // 检查是否充电中
    if (CARingSDK.instance.currentDevice.isCharging) {
        [self showAlertWarningWithTitle:@"Tips" Msg:@"The ring is charging.\r\nTo start an ECG measurement, remove the ring from the charger and put it on your finger." btnOk:@"Ok" OkBLk:^{
            
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
        return;
    }
    
    if (![CARingSDK.instance hasECGKeyAndSecret]) {
        [self showAlertWarningWithTitle:@"Tips" Msg:@"You cannot perform measurement because the parameters KEY and SECRET required for requesting the server API cannot be read.\r\nYou need to fill in your own KEY and SECRET in the API call: registECGKey: Secret: and then recompile the project.\r\nFor the acquisition of these two parameters, please contact our technical support." btnCancel:@"Ok" Compelete:^{
            
        }];
        return;
    }
    
    if (!self.deviceInfo) {
        [self showAlertWarningWithTitle:@"Tips" Msg:@"Please obtain device information first." btnCancel:@"Ok" Compelete:^{
            
        }];
        return;
    }
    
    self.ecgRecord = [[CAEcgRecord alloc]init];
    self.ecgRecord.startTs = @((NSInteger)[NSDate date].timeIntervalSince1970);
    self.ecgRecord.wearHand = self.wearHand.intValue;
    
    CAEcgParamObj *param = [CAEcgParamObj defaultLocalAlgorithemParam];// 戒指计算ecg
    if (!self.useLocalAlgothem) { // 使用网络计算ecg
        param = [CAEcgParamObj defaultNetAlgorithemParam];
    }
    
    self.ecgRecord.isRingAlgorithm = !param.isRowWave;

//    self.hmEcgDrawLineView.ecgParamObj = param;
    self.ecgResultArray = [NSMutableArray new];
//    self.volArray = [NSMutableArray new];

    self.measuring = YES;
    DebugNSLog(@"ecg 指令 下发开始");
    
    [self.realMeaDrawLineView setHorizonalSpeed:self.xSpeed VertialGain:self.yGain];
    [self.hisDrawLineView setHorizonalSpeed:self.xSpeed VertialGain:self.yGain];

    // 重设采样率
    [self setAlgoObjSampleRate:self.ecgRecord.frequencyValue Obj:self.algoEcgSdkObj];
    [self.algoEcgSdkObj resetECGAnalysis];//重置滤波
    
    self.netFiltWaveArray = [NSMutableArray new];
    
    self.ecgRecord.firmWare = self.deviceInfo.softWareVersion;//[DeviceCenter instance].bindDevice.otherInfo.fireWareVersion;
    
    [self.realMeaDrawLineView setFreqType:self.ecgRecord.frequencyType == ECG_FREQ_512 ? ECG_DR_LINE_FRQ_512 : ECG_DR_LINE_FRQ_500 ];
    self.state = CA_ECG_MEA_STA_WAIT_LEADON; //进入测量中状态
    self.isRequestingNet = NO;
    
    [CARingSDK.instance functionECGMeasure:YES Param:param DispSrc:param.isRowWave];

    
//    dispatch_resume(self.timer);
}

-(void)stopEcgMeasure {
    self.measuring = NO;
    DebugNSLog(@"ecg 指令 下发结束 1");

    [CARingSDK.instance functionECGMeasure:NO Param:nil DispSrc:YES];

}

// 整理并显示结果数值
-(void)sumAndShowResult {
    [self sumResult]; // 整理结果

    [self showResult]; // 显示结果
}


// 总结结果
-(void)sumResult
{
    if(!self.ecgRecord.endTs) {
        self.ecgRecord.endTs = @((NSInteger)[NSDate date].timeIntervalSince1970);
    }
//    DebugNSLog(@"波形数量 %lu", (unsigned long)self.ecgRecord.volArray.count);
    if (self.ecgRecord.volArray.count < (self.sampleRate * self.measuSecondsLimit)) {
        DebugNSLog(@"数量不足, 波形数量 %lu", self.ecgRecord.volArray.count);

        self.ecgRecord.conclusion = CONCLUSION_NOT_ENOUGH_TIME;
        return;
    }
    
    if (self.useLocalAlgothem) {
        CAEcgAlgorithmResults *lastRes = self.ecgResultArray.lastObject;
        if (lastRes) {
            [self.ecgRecord setValuesWith:lastRes];

        }
    }
    
  
//    self.ecgRecord.volArray = self.volArray;  // 波形
    
//    __block NSInteger total = 0;
//    __block NSInteger count = 0;
//    [self.ecgResultArray enumerateObjectsUsingBlock:^(SrEcgAlgorithmResults * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (obj.heartRate > 40 && obj.heartRate < 254) {
//            total += obj.heartRate;
//            count++;
//        }
//    }];
//    if (total > 0) {
//        self.ecgRecord.avgHeartRate = @((int)(total*1.0/count));
//    }
    
    
}

/// 显示结论信息
/// - Parameter btn:btn
//-(void)gotoShowInfo:(UIButton *)btn {
//    MEDIC_ECG type = [EcgMedicObj transConclusionToMedicType:self.ecgRecord.conclusion];
//    ECGMedicVc *vc = [[ECGMedicVc alloc]init];
//    vc.type = type;
//    vc.hidesBottomBarWhenPushed = YES;
//    
//    [self.navigationController pushViewController:vc animated:YES];
//}

-(void)showResult {

    
    if (self.ecgRecord.avgHeartRate) {
        self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %d%@", @"Avg.", self.ecgRecord.avgHeartRate.intValue, @"bpm"];

    } else {
        self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %@%@", @"Avg.", NONE_VALUE, @"bpm"];
    }
    
    self.topLabel.text = [CAEcgRecord titleOfConclusion:self.ecgRecord.conclusion];
    self.hrDescLbl.text = [CAEcgRecord descOfConclusion:self.ecgRecord.conclusion];
    
}

/// 弹出手指无接触提示
-(void)showEcgUseDescView {
    
    if (self.noTouchTipView) {
        return;
    }
    
    EcgNoTouchTipView *tipView = [[EcgNoTouchTipView alloc]init];
    WEAK_SELF
    tipView.closeBlk = ^{
        STRONG_SELF
        DebugNSLog(@"提示关闭");
        // 停止测量
        [strongSelf stopEcgMeasure];
        [strongSelf sumAndShowResult];

        // 提前结束
        strongSelf.state = CA_ECG_MEA_STA_INIT; // 回到初始状态
    };
    // tipView
    [((AppDelegate *)([UIApplication sharedApplication].delegate)).window addSubview:tipView];
    self.noTouchTipView = tipView;
    [tipView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(tipView.superview);
    }];
}

-(void)hideEcgUseDescView {
    [self.noTouchTipView removeFromSuperview];
}


//-(void)showEcgChooseSymptomsView {
//    
//    if (self.chooseSymptomsView) {
//        return;
//    }
//    
//    EcgSymptomChooseView *chooseView = [[EcgSymptomChooseView alloc]init];
//    chooseView.symptoms = self.symptomSelectView.symptomsArray;
//    WEAK_SELF
//    chooseView.closeBlk = ^{
//        STRONG_SELF
//        DebugNSLog(@"提示关闭");
//    };
//    
//    chooseView.saveBlk = ^(NSMutableArray<NSNumber *> * _Nullable symptoms) {
//        STRONG_SELF
//        strongSelf.symptomSelectView.symptomsArray = symptoms;
//        strongSelf.ecgRecord.symptomsArray = symptoms;
//        
//        [strongSelf.mainContent layoutIfNeeded];
//        [strongSelf.scrollView layoutIfNeeded];
//    };
//    // tipView
//    [((AppDelegate *)([UIApplication sharedApplication].delegate)).window addSubview:chooseView];
//    self.chooseSymptomsView = chooseView;
//    [chooseView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.top.bottom.equalTo(chooseView.superview);
//    }];
//}

-(void)done:(QMUIButton *)done {
    
    [[LTPHud Instance]showHudLasting:1.5];
    [self.ecgRecord updateSymptoms:^(BOOL succ) {
        
    }];
    
    self.state = CA_ECG_MEA_STA_INIT; // 回到初始
}


-(void)setState:(CA_ECG_MEA_STA)state
{
    _state = state;
    
    switch (_state) {
        case CA_ECG_MEA_STA_INIT: // 初始状态
        {
//            self.symptomSelectView.symptomsArray = nil;
//            self.symptomSelectView.hidden = YES;
            self.resTipLbl.hidden = YES;
            self.hrItem.hidden = YES;
            self.startBtn.selected = NO;
            self.startBtn.hidden = NO;
            self.xSpeedBtn.hidden = NO;
            self.yGainBtn.hidden = NO;

//            self.startBtn.backgroundColor = MAIN_BLUE;
            self.doneBtn.hidden = YES;

            self.hrItem.titleLbl.text = nil;
//            self.countTimes = ECG_MESURING_DURA_SECS_FOR_LOCAL;
            self.topLabel.text = nil;
            self.hrDescLbl.hidden = YES;
            self.hrDescLbl.text = nil;
            
            self.realMeaDrawLineView.hidden = NO;
            self.realGridView.hidden = NO;
            self.hisDrawLineView.hidden = YES;
            
            [self.realMeaDrawLineView reset];
            [self.hisDrawLineView reset];
            [self hideEcgUseDescView]; // 隐藏接触提示
//            [self.measuProgressView setProgress:0 animated:NO];
           
            [self.mainContent layoutIfNeeded];
            [self.view layoutIfNeeded];
//            self.infoBtn.hidden = YES;
            self.wearHandSeg.enabled = YES;
            
        }
            break;
        case     CA_ECG_MEA_STA_WAIT_LEADON:
        {
            // 显示手指提示view
            [self showEcgUseDescView];
            // 重置 定时器 波形数组 画图view
            self.ecgRecord.volArray = [NSMutableArray new];
            self.netFiltWaveArray = [NSMutableArray new];
            [self.hisDrawLineView reset];
            self.ignoreCount = 0; // 忽略数据计数
            self.wearHandSeg.enabled = NO;

//            [self stopTimer];
            
        }
            break;
        case     CA_ECG_MEA_STA_MEASURING: // 测量中状态
        {
            self.wearHandSeg.enabled = NO;

            // 隐藏 leadon view
            [self hideEcgUseDescView];
            // 定时器启动
//            [self startTimer];
//            self.measuProgressView.hidden = NO;
            
            self.topLabel.text = @"Ready to measure...";
            if (self.deviceInfo.ecgCalcType == CA_ECG_CALC_ON_DEVICE) {
               // 设备算ecg才显示
                self.hrItem.hidden = NO;
            }
            
            self.hrDescLbl.hidden = NO;

            self.startBtn.selected = YES;
            self.startBtn.hidden = YES;
            self.xSpeedBtn.hidden = YES;
            self.yGainBtn.hidden = YES;
//            self.startBtn.backgroundColor = BUTTON_RED;
            
            self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %@", NONE_VALUE, @"bpm"];
            self.hrDescLbl.text = @"Note: It cannot detect a heart attack.";
            self.resTipLbl.hidden = YES;
//            self.symptomSelectView.hidden = YES;
            self.hrImageView.hidden = NO;
        }
            break;
        case     CA_ECG_MEA_STA_DONE: // 等待用户done状态
        {
//            self.startBtn.selected = NO;
//            self.startBtn.backgroundColor = MAIN_BLUE;
            self.resTipLbl.hidden = NO;
//            self.symptomSelectView.hidden = NO;
            self.hrImageView.hidden = NO;
            self.hrItem.hidden = NO;
            // 保存
//            [self.ecgRecord insert:^(BOOL succ) {
//                
//            }];
            self.startBtn.hidden = YES;
            self.xSpeedBtn.hidden = YES;
            self.yGainBtn.hidden = YES;
            self.doneBtn.hidden = YES;
            
            self.realMeaDrawLineView.hidden = YES;
            self.realGridView.hidden = YES;
            self.hisDrawLineView.hidden = NO;
            self.hisDrawLineView.drawLineView.direction = self.ecgRecord.wearHand;
            
            self.hisDrawLineView.ecgRecord = self.ecgRecord;
            [self.hisDrawLineView drawAllData:self.ecgRecord.volArray];
//            self.infoBtn.hidden = NO;
            
        }
            break;
        case     CA_ECG_MEA_STA_ERROR:
        {
            [self stopEcgMeasure];
            [self sumAndShowResult];
            self.wearHandSeg.enabled = YES;

        }
            break;
            
        default:
            break;
    }
}

#pragma mark -- ECG 神念
// 神念滤波回调
- (void)dataReceived:(ECGAlgorithmsData)algo results:(int)value {
    if (algo == ECG_SMOOTHED_WAVE) { // 波形处理

//        if ([self.bleDataDelegate respondsToSelector:@selector(srBleEcgWave:)]) {
//            SrEcgData *data = [[SrEcgData alloc]init];
//            data.type = SRECG_TYPE_ONLY_ECG;
//            data.ecgArray = [NSMutableArray new];
//            [data.ecgArray addObject:@(value)];
//            [self.bleDataDelegate srBleEcgWave:data];
//        }
//        DebugNSLog(@"ecg wave 神念:%d", value);
        [self cacheAndCaculate:@[@(value)]];

    }
}


#pragma  mark --蓝牙代理
- (void)caBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging {
    
   
    
    if (self.state == CA_ECG_MEA_STA_INIT && isCharging) {
        self.chargeTipLbl.hidden = NO;
    } else {
        self.chargeTipLbl.hidden = YES;
    }
}

- (void)caBleDeviceDidReadyForReadAndWrite:(nonnull CABLeService *)service {
    
}

- (void)caBleDeviceInfo:(nonnull CADeviceInfo *)devInfo {
    
}

- (void)caBleDeviceRealtimeSteps:(nonnull NSNumber *)steps IsDeviceFix:(BOOL)isDeviceFixed {
    
}

- (void)caBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature {
    
}

- (void)caBleDidConnectPeripheral:(nonnull CABLeService *)service {
    self.startBtn.enabled = YES;
   
}

- (void)caBleDidDisconnectPeripheral:(nonnull CABLeService *)service {
    
    
    self.chargeTipLbl.hidden = YES;
    
    if (self.state ==     CA_ECG_MEA_STA_WAIT_LEADON
        || self.state ==     CA_ECG_MEA_STA_MEASURING) {
        WEAK_SELF
        self.state =     CA_ECG_MEA_STA_ERROR;
        [self showAlertWarningWithTitle:@"Tups" Msg:@"Ring disconnected, stop ECG measurement." btnOk:@"Ok" OkBLk:^{
            STRONG_SELF
            
            strongSelf.state = CA_ECG_MEA_STA_INIT;
            
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
    }
    
    self.startBtn.selected = NO;
    self.startBtn.hidden = NO;
    self.xSpeedBtn.hidden = NO;
    self.yGainBtn.hidden = NO;
//    self.startBtn.backgroundColor = MAIN_BLUE;

    self.startBtn.enabled = NO;
    
    
}

-(void)caBleEcgEcgLeadOn:(BOOL)leadOn
{
    // 手指检测 yes = 手指接触  no = 手指松开
    DebugNSLog(@"手指接触 %d", leadOn);
    if (self.state ==     CA_ECG_MEA_STA_WAIT_LEADON) {
        DebugNSLog(@"手指  ECG_MEA_STA_WAIT_LEADON %d", leadOn);
        // 初始状态
        if (leadOn == YES) {
            // 进入测量中状态
            self.state =     CA_ECG_MEA_STA_MEASURING;
        }
        return;
    }
    
    if (self.state ==     CA_ECG_MEA_STA_MEASURING) {
        DebugNSLog(@"手指  ECG_MEA_STA_MEASURING %d", leadOn);

        // 测量中的断开
        if (leadOn == NO) {
            // 进入 等待leanon
            self.state =     CA_ECG_MEA_STA_WAIT_LEADON;
        }
        
    }
    
}


- (void)caBleHistoryData:(nonnull CAHistoryData *)hisData IsComplete:(BOOL)isComplete {
    
}

- (void)caBleHistoryDataCount:(NSInteger)count {
    
}

- (void)caBleHistoryDataTimeout {
    
}

- (void)caBleHistorySr03Data:(nonnull CAHistoryDataSR03 *)hisData IsComplete:(BOOL)isComplete {
    
}

- (void)caBleMeasureDuration:(NSInteger)seconds {
    
}

- (void)caBleOEMAuthResult:(BOOL)authSucceddful {
    
}



- (void)caBleRealtimeHRV:(nonnull NSNumber *)hrv BloodOxygen:(nonnull NSNumber *)bloodOxygen HeartRate:(nonnull NSNumber *)hr Status:(REALTIME_STATUS)status {
    
}

- (void)caBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData {
    
}

- (void)caBleSOShappen {
    
}

- (void)caBlesSOSData:(float)temperature HeartRate:(NSInteger)hr BloodOxygen:(NSInteger)bloodOxygen {
    
}

-(void)caBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CA_CMD_EXECTE_ERROR_REASON)reason Data:(NSData *)originData
{
    if (cmd == EXCUTED_CMD_FUNCTIN_ECG
        && !isSucc && self.state != CA_ECG_MEA_STA_INIT
       ) {
        DebugNSLog(@"ecg 指令 fail, reason %lu data:%@", (unsigned long)reason, originData);
        NSString *string = [CADeviceInfo descryOfErrorReason:reason];
        if (string.length) {
            WEAK_SELF
            [self showAlertWarningWithTitle:@"Tips" Msg:string btnOk:_L2(L_OK) OkBLk:^{
                STRONG_SELF
            } CancelBtn:nil CancelBlk:nil Compelete:nil];
            
            self.state = CA_ECG_MEA_STA_INIT; // 还原状态
            if (reason == CA_REASON_3) {
                DebugNSLog(@"ecg 指令 下发结束 2");
                self.measuring = NO;
                [CARingSDK.instance functionECGMeasure:NO Param:nil DispSrc:YES];
            }
        }
    }
    
}

/// 回调ecg波形
-(void)caBleEcgWave:(CAEcgData *)ecgObj
{
    if (self.state == CA_ECG_MEA_STA_INIT) {
        return;
    }
    
    for (NSNumber * ecg in ecgObj.ecgArray) {
//        [ecgObj.ecgArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            DebugNSLog(@"ecg ori:%@", ecg);
//        }];
        
        // 传入神念 25-1-9改
        [self.algoEcgSdkObj requestECGAnalysis:ecg.intValue withPoorSignal:200];
        
    }

   
    if (!self.useLocalAlgothem) { // 使用网络计算ecg
        
        NSMutableArray <NSNumber *> *volArray = [NSMutableArray new];
        [ecgObj.ecgArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSNumber *transVol = @([CARingSDK.instance.ecgParamObj transWaveToVol:obj.floatValue]);// 转电压
            [volArray addObject:transVol];
//            DebugNSLog(@"ecg 波 %@, vol %@",  obj, transVol);
        }];
        
      
        int second = 5;
        BOOL canAdd = self.ignoreCount >= (second * self.sampleRate); // Discard the first few seconds of data
        
        if (canAdd) {
            if (self.netFiltWaveArray.count <= (self.sampleRate * self.measuSecondsLimit)) {
                [self.netFiltWaveArray addObjectsFromArray:volArray];

            }
        }
        
    }
    

}

-(void)cacheAndCaculate:(NSArray<NSNumber *> *)waveArray
{
    if (!waveArray.count) {
        return;
    }
    
    NSMutableArray <NSNumber *> *volArray = [NSMutableArray new];
    [waveArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSNumber *transVol = @([CARingSDK.instance.ecgParamObj transWaveToVol:obj.floatValue]);// 转电压

        
        [volArray addObject:transVol];
//        DebugNSLog(@"ecg 波-神念后 %@, vol %@",  obj, transVol);
    }];
    
    if (!self.ecgRecord.volArray.count) { // 过滤开头的0值
        [self.realMeaDrawLineView updateValues:volArray]; // 画图
        
        BOOL canAdd = NO;//NO;
        
        if (self.useLocalAlgothem && self.ecgResultArray.lastObject.alive ) {
            canAdd = YES;
        }
        
        if ( !self.useLocalAlgothem) {
            self.ignoreCount += volArray.count;
            int second = 5;
            canAdd = self.ignoreCount >= (second * self.sampleRate); // Discard the first few seconds of data
        }
        
        if (canAdd) {
            
            
            // 戒指算法 从第一个标记为用户心跳的位置开始
            [self.ecgRecord.volArray addObjectsFromArray:volArray];
            // 剩余几秒
            int restSeconds = ((self.sampleRate * self.measuSecondsLimit) - (int)self.ecgRecord.volArray.count) / self.sampleRate;
            if (restSeconds < 0) {
                restSeconds = 0;
            }
            //                    DebugNSLog(@"剩余 %d 秒", restSeconds);
            self.topLabel.text = [NSString stringWithFormat:@"%@%d%@", @"Estimated time remaining:", restSeconds, @"s"];
            
            
        }
        return;
    }
    
    if (self.ecgRecord.volArray.count <= (self.sampleRate * self.measuSecondsLimit)) {
        //
        if (self.state ==     CA_ECG_MEA_STA_MEASURING) { // 避免leadon = off时存0值
            // 测量数据不够
            [self.realMeaDrawLineView updateValues:volArray];
            [self.ecgRecord.volArray addObjectsFromArray:volArray];
            // 剩余几秒
            int restSeconds = (self.sampleRate * self.measuSecondsLimit - (int)self.ecgRecord.volArray.count) / self.sampleRate;
            if (restSeconds < 0) {
                restSeconds = 0;
            }
            //                DebugNSLog(@"剩余 %d 秒", restSeconds);
            self.topLabel.text = [NSString stringWithFormat:@"%@%d%@", @"Estimated time remaining:", restSeconds, @"s"];
        }
        
        
    } else {
        if (self.useLocalAlgothem) { // 原逻辑
            if (self.state !=     CA_ECG_MEA_STA_DONE) {
                DebugNSLog(@"准备停止, 数组数量 %lu", self.ecgRecord.volArray.count);
                // 切换为停止状态
                [self stopEcgMeasure]; //停止测量
                [self sumAndShowResult];
                
                self.state =     CA_ECG_MEA_STA_DONE;
            }
        }
        
        if (!self.useLocalAlgothem) {
            // 使用网络计算ecg
            if (!self.isRequestingNet) {
                self.isRequestingNet = YES;
                self.ignoreCount = 0;
                self.state =     CA_ECG_MEA_STA_WAIT_NET_ANALY; // 中间状态, 避免leadon触发
                
                [self stopEcgMeasure]; //停止测量
                // 网络请求
                
                NSArray<NSNumber *> *reqRowArr = self.netFiltWaveArray;//self.ecgRecord.volArray;
                DebugNSLog(@"网络ecg 神念滤波后数量 %lu, 原始数量 %lu", self.ecgRecord.volArray.count, self.netFiltWaveArray.count);
                if(!self.ecgRecord.endTs) {
                    self.ecgRecord.endTs = @((NSInteger)[NSDate date].timeIntervalSince1970);
                }
                
                [[LTPHud Instance] showHudLasting:15];
                // mac 转小写
                NSString * mac = [CARingSDK.instance.currentDevice.macAddress lowercaseString];
                NSString *sign = [CARingSDK.instance signStringWith:CARingSDK.instance.currentDevice.snString MacAddr:mac];
                WEAK_SELF
                [EcgNetReq ecgNetRowWaveFilter:[NSString stringWithFormat:@"%@", HOSTNAME]
                                     DataArray:reqRowArr
                                           Key:CARingSDK.instance.netKey
                                            Sn:CARingSDK.instance.currentDevice.snString
                                       MacAddr:mac
                                          Sign:sign
                                  AndComplated:^(NSHTTPURLResponse * _Nullable httpResp, NSDictionary * _Nullable content, NSArray<NSNumber *> * _Nullable processedValues)
                 {
                    STRONG_SELF
                    if (httpResp.statusCode != 200) {
                        // error
                        strongSelf.isRequestingNet = NO;
//                        [strongSelf stopEcgMeasure];
                        
                        strongSelf.state = CA_ECG_MEA_STA_INIT;//ECG_MEA_STA_ERROR;
                        [LTPHud.Instance showText:_L2(L_NET_FAIL_COM_TIP) Lasting:2.5];
                        //                            [[LTPHud Instance] hideHud];
                        return;
                    }
                    
                    // 服务器滤波结果存储
                    
                    [strongSelf.ecgRecord acceptFilterArray:processedValues];
                    
                    NSString * mac = [CARingSDK.instance.currentDevice.macAddress lowercaseString];

                    NSString *sign = [CARingSDK.instance signStringWith:CARingSDK.instance.currentDevice.snString MacAddr:mac];
                    
                    [EcgNetReq ecgNetArrhythmia:[NSString stringWithFormat:@"%@", HOSTNAME]
                                      DataArray:reqRowArr
                                            Key:CARingSDK.instance.netKey
                                             Sn:CARingSDK.instance.currentDevice.snString
                                        MacAddr:mac
                                           Sign:sign
                                   AndComplated:^(NSHTTPURLResponse * _Nullable httpResp, NSDictionary * _Nullable content, NSArray<NSNumber *> * _Nullable processedValues) {
                        STRONG_SELF
                        
                        [strongSelf.ecgRecord analyFromNetArrhythmia:content];
                        [[LTPHud Instance] hideHud];
                        [strongSelf showResult]; //显示结果
                        strongSelf.state =     CA_ECG_MEA_STA_DONE;
                        strongSelf.isRequestingNet = NO;
                        
                        
                    } AndServerNil:^{
                        
                    }];
                    
                    
                } AndServerNil:^{
                    
                }];
                
            }
        }
        
    }
}


// ecg+ ppg混合
-(void)caBleEcgAndPPgWave:(CAEcgData *)ecgPpgObj
{
   
}

// 回调ecg计算结果
-(void)caBleEcgAlgorithmResult:(CAEcgAlgorithmResults *)ecgResult
{
    
    [self.ecgResultArray addObject:ecgResult];
  
//    DebugNSLog(@"ecg 用户连接: %d", ecgResult.present );
    self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%d %@", ecgResult.heartRate, @"bpm"];
    if (ecgResult.avgHeartrate > 40 && ecgResult.avgHeartrate < 200) {
        self.ecgRecord.avgHeartRate =  @(ecgResult.avgHeartrate);
    }
    
//    if (ecgResult.alive && self.state == ECG_MEA_STA_MEASURING) {
        //检测到活体生物 开始采集数据 计时
//        self.topLabel.text = nil;
//    }
    
    
//    [self printEcgResult:ecgResult];
    
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width, CGRectGetMaxY(self.mainContent.frame));

}


#pragma mark --lazy
- (QMUIButton *)startBtn
{
    if (!_startBtn) {
        _startBtn = [[QMUIButton alloc]init];
        _startBtn.backgroundColor = MAIN_BLUE;
        
        _startBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_startBtn setTitle:@"Start" forState:UIControlStateNormal];
//        [_startBtn setTitle:_L2(L_EARLY_END) forState:UIControlStateSelected];

        [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_startBtn addTarget:self action:@selector(startEcg:) forControlEvents:UIControlEventTouchUpInside];
        _startBtn.enabled = NO; // 初始不可用
    }
    return _startBtn;
}



-(QMUIButton *)xSpeedBtn
{
    if (!_xSpeedBtn) {
        _xSpeedBtn = [[QMUIButton alloc]init];
        _xSpeedBtn.backgroundColor = MAIN_BLUE;
        
        _xSpeedBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_xSpeedBtn setTitle:_xspeedArray[0][@"title"] forState:UIControlStateNormal];
//        [_startBtn setTitle:_L2(L_EARLY_END) forState:UIControlStateSelected];

        [_xSpeedBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_xSpeedBtn addTarget:self action:@selector(chooseXspeed:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _xSpeedBtn;
}

-(QMUIButton *)yGainBtn
{
    if (!_yGainBtn) {
        _yGainBtn = [[QMUIButton alloc]init];
        _yGainBtn.backgroundColor = MAIN_BLUE;
        
        _yGainBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_yGainBtn setTitle:_yGainArray[1][@"title"] forState:UIControlStateNormal];
//        [_startBtn setTitle:_L2(L_EARLY_END) forState:UIControlStateSelected];

        [_yGainBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_yGainBtn addTarget:self action:@selector(chooseYgain:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _yGainBtn;
}

-(QMUIButton *)doneBtn
{
    //
    if (!_doneBtn) {
        _doneBtn = [[QMUIButton alloc]init];
        _doneBtn.backgroundColor = MAIN_BLUE;
        
        _doneBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_doneBtn setTitle:@"End" forState:UIControlStateNormal];

        [_doneBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_doneBtn addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
        _doneBtn.hidden = YES;
    }
    return _doneBtn;
}

-(LTRingEcgDrawLineView *)realMeaDrawLineView
{
    if (!_realMeaDrawLineView) {
        LTRingEcgDrawLineView *lineView = [[LTRingEcgDrawLineView alloc]init];
        lineView.backgroundColor = UIColor.clearColor;
//        NSNumber *spType = @(self.xSpeed);
//        NSNumber *ygainType = @(self.yGain);
        
        lineView.direction = self.wearHand.intValue;
        
        [lineView setHorizonalSpeed:self.xSpeed VertialGain:self.yGain];
        lineView.ecgLineColor = BUTTON_RED;
        _realMeaDrawLineView = lineView;
    }
    
    return _realMeaDrawLineView;
}



-(UILabel *)hrDescLbl
{
    if (!_hrDescLbl)
    {
        _hrDescLbl = [UILabel new];
        _hrDescLbl.numberOfLines = 0;
        _hrDescLbl.adjustsFontSizeToFitWidth = YES;
        _hrDescLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:16];
    }
    return _hrDescLbl;
}



-(ImgTitleItem *)hrItem
{
    if (!_hrItem) {
        _hrItem = [[ImgTitleItem alloc]init];
        _hrItem.imageView.image = [UIImage imageNamed:@"ecg_hr"];
        _hrItem.titleLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:17];
        
    }
    return _hrItem;
}

-(UILabel *)resTipLbl
{
    if (!_resTipLbl) {
        _resTipLbl = [UILabel new];
        _resTipLbl.textColor = UIColor.lightGrayColor;
        _resTipLbl.font = [UIFont systemFontOfSize:14];
        _resTipLbl.numberOfLines = 0;
        _resTipLbl.adjustsFontSizeToFitWidth = YES;
        _resTipLbl.text = @"If you believe you've having a heart attack or a medical emergency, call emergency services.";
    }
    
    return _resTipLbl;
}

// 充电中提示
-(UILabel *)chargeTipLbl
{
    if (!_chargeTipLbl) {
        _chargeTipLbl = [UILabel new];
        _chargeTipLbl.font = [UIFont systemFontOfSize:15];
        _chargeTipLbl.numberOfLines = 0;
        _chargeTipLbl.adjustsFontSizeToFitWidth = YES;
        _chargeTipLbl.text = @"The ring is charging.\r\nTo start an ECG measurement, remove the ring from the charger and put it on your finger.";
        _chargeTipLbl.textColor = UIColor.redColor;
    }
    
    return _chargeTipLbl;
}

//-(SymptomsBtnView *)symptomSelectView
//{
//    if (!_symptomSelectView) {
//        _symptomSelectView = [[SymptomsBtnView alloc]init];
//        WEAK_SELF
//        _symptomSelectView.clickBlk = ^{
//            STRONG_SELF
//            [strongSelf showEcgChooseSymptomsView];
//        };
//    }
//    return _symptomSelectView;
//}

-(CARingEcgDrawHistoryView *)hisDrawLineView
{
    if (!_hisDrawLineView) {
        _hisDrawLineView = [[CARingEcgDrawHistoryView alloc]init];
        NSNumber *spType = @(self.xSpeed);
        NSNumber *ygainType = @(self.yGain);

        _hisDrawLineView.drawLineView.direction = self.wearHand.intValue;
        
        [_hisDrawLineView setHorizonalSpeed:spType.unsignedIntValue VertialGain:ygainType.unsignedIntValue];
        _hisDrawLineView.ecgLineColor = BUTTON_RED;
    }
    return _hisDrawLineView;
}

//-(UIProgressView *)measuProgressView
//{
//    if (!_measuProgressView) {
//        _measuProgressView = [[UIProgressView alloc]init];
//        //        _syncHisDataProgressView.transform = CGAffineTransformMakeScale(1.0, 0.5);
//        _measuProgressView.trackTintColor = [UIColor lightGrayColor]; // 轨道颜色
//        _measuProgressView.progressTintColor = MAIN_BLUE; // 进度颜色
//        _measuProgressView.hidden = YES;
//    }
//    return _measuProgressView;
//}

-(UIScrollView *)scrollView
{
    if(!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

//-(UIButton *)infoBtn
//{
//    if (!_infoBtn) {
//        
//        UIButton *infoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [infoBtn setImage:[UIImage imageNamed:@"info"] forState:UIControlStateNormal];
//        [infoBtn addTarget:self action:@selector(gotoShowInfo:) forControlEvents:UIControlEventTouchUpInside];
//        _infoBtn = infoBtn;
//    }
//    return _infoBtn;
//}

@end


// 测试的函数
@implementation CAEcgMeasureVc (Test)

-(SepLineView *)creatSepLine {
    SepLineView *sep = [[SepLineView alloc]init];
    sep.lineColor = SEPLINE_COLOR(0.7);
    sep.isDash = YES;
    return sep;
}

-(NSKAlgoSDKECG *)algoEcgSdkObj
{
    if (!_algoEcgSdkObj) {
      
        _algoEcgSdkObj = [[NSKAlgoSDKECG alloc]init];
        [_algoEcgSdkObj setDelegate:self];
        
//        NSString * licenseKey = @"4DYD5nkbZHYoJBqIxT3nc/QIB58doR7BiRxuH62Ayhs=";
        int sampleRate = 512;// 默认给一个
//        [_algoEcgSdkObj setupSDKProperty:NSKAlgolicenseKey withSampleRate:sampleRate enableSmoothed:1];
        [self setAlgoObjSampleRate:sampleRate Obj:_algoEcgSdkObj];
        
        [_algoEcgSdkObj enableNSLogMessages:false];
    }
    return _algoEcgSdkObj;
}

-(UISegmentedControl *)wearHandSeg
{
    if (!_wearHandSeg) {
        
        NSArray<NSString *> *titles =@[@"Left hand", @"Right hand"];
        _wearHandSeg = [[UISegmentedControl alloc]initWithItems:titles];
        _wearHandSeg.selectedSegmentIndex = 0; // 默认选中
        [_wearHandSeg addTarget:self action:@selector(segSelect:) forControlEvents:UIControlEventValueChanged];
        _wearHandSeg.selectedSegmentTintColor = MAIN_BLUE;
        
    }
    return _wearHandSeg;
}


@end
